package com.icu.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.icu.controller.request.user.UserAddRequest;
import com.icu.controller.request.user.UserLoginRequest;
import com.icu.controller.request.user.UserListRequest;
import com.icu.entity.User;
import com.icu.entity.UserShippingAddress;
import com.icu.enums.ErrorEnum;
import com.icu.mapper.UserMapper;
import com.icu.service.IUserService;
import com.icu.util.RUtil;
import com.icu.vo.user.UserShippingAddressVO;
import com.icu.vo.user.UserVO;
import com.icu.vo.user.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Resource
    private CaptchaService captchaService;

    @Resource
    private UserMapper userMapper;

    /**
     * 添加
     */
    @Override
    public RUtil add(UserAddRequest request) {

        ResponseModel verification = captchaVerification(request.getCaptchaVerification());

        if (!verification.isSuccess()) {
            //return RUtil.error(Integer.parseInt(verification.getRepCode()), verification.getRepMsg());
        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();

        String phone = request.getPhone();

        wrapper.eq("phone", phone);

        User info = userMapper.selectOne(wrapper);

        if (info != null) {
            return RUtil.errorEnum(ErrorEnum.USER_REPEAT);
        }

        String shaPwd = SaSecureUtil.sha256(request.getPwd());

        User user = new User();

        user.setPhone(request.getPhone());
        user.setNickname(request.getNickname());
        user.setAddTime(DateUtil.date());
        user.setPwd(shaPwd);

        int insert = userMapper.insert(user);

        return insert == 1 ? RUtil.success() : RUtil.errorEnum(ErrorEnum.USER_REGISTER_FAIL);
    }

    /**
     * 登录
     */
    @Override
    public RUtil login(UserLoginRequest request) {

        ResponseModel verification = captchaVerification(request.getCaptchaVerification());

        if (!verification.isSuccess()) {
            //return RUtil.error(Integer.parseInt(verification.getRepCode()), verification.getRepMsg());
        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();

        String phone = request.getPhone();

        wrapper.eq("phone", phone);

        User userInfo = userMapper.selectOne(wrapper);

        if (userInfo == null) {
            return RUtil.errorEnum(ErrorEnum.USER_PWD_ERROR);
        }

        String shaPwd = SaSecureUtil.sha256(request.getPwd());

        if (!shaPwd.equals(userInfo.getPwd())) {
            return RUtil.errorEnum(ErrorEnum.USER_PWD_ERROR);
        }

        StpUtil.login(userInfo.getId());

        UserLoginVO userLoginVO = new UserLoginVO();

        BeanUtils.copyProperties(userInfo, userLoginVO);

        userLoginVO.setSatoken(StpUtil.getTokenValue());

        return RUtil.success(userLoginVO);
    }

    /**
     * 列表
     */
    @Override
    public Map<String, Object> list(UserListRequest request) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();

        if (!request.getPhone().equals("")) {
            wrapper.likeRight("phone", request.getPhone());
        }

        if (!request.getNickname().equals("")) {
            wrapper.likeRight("nickname", request.getNickname());
        }

        IPage<User> page = new Page<>(request.getCurrent(), request.getSize());

        List<User> userList =  userMapper.list(page, wrapper);

        List<UserVO> userVOList = userList.stream().map(this::beanUser).collect(Collectors.toList());

        Map<String, Object> data = new HashMap<>();

        data.put("list", userVOList);

        return data;
    }

    /**
     * 滑动验证码二次校验接口
     */
    private ResponseModel captchaVerification(String captchaVerification) {
        CaptchaVO captchaVO = new CaptchaVO();

        captchaVO.setCaptchaVerification(captchaVerification);

        return captchaService.verification(captchaVO);
    }

    /**
     * 处理用户
     */
    private UserVO beanUser(User user) {

        UserVO userVO = new UserVO();

        BeanUtils.copyProperties(user, userVO);

        List<UserShippingAddressVO> addressVO = user.getShippingAddress().stream().map(this::beanShippingAddress).collect(Collectors.toList());

        userVO.setShippingAddress(addressVO);

        return userVO;
    }

    /**
     * 处理收货地址
     */
    private UserShippingAddressVO beanShippingAddress(UserShippingAddress address) {

        UserShippingAddressVO addressVO = new UserShippingAddressVO();

        BeanUtils.copyProperties(address, addressVO);

        return addressVO;
    }

}
